/*
 * Copyright (C) 2008 Matt Falkoski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.falko.android.raven.util;

import java.util.Random;

import com.falko.android.raven.RavenWallpaperService.RavenWallpaperEngine;

public class AutoSpawnThread implements Runnable {

	private RavenWallpaperEngine engine_ = null;
	private Thread thread_;
	private Object threadLock_ = new Object();
	private volatile int interval_ = 500;
	private boolean threadPaused_ = true;
	private boolean threadRunning_ = false;
	private int width_ = 50;
	private int height_ = 50;

	public AutoSpawnThread(RavenWallpaperEngine engine) {
		engine_ = engine;
		thread_ = new Thread(this);
		thread_.start();
	}

	public void setInterval(int i) {
		synchronized (threadLock_) {
			interval_ = i * 100;
		}
		threadRunning_ = true;
	}

	public void setDimentions(int width, int height) {
		width_ = width;
		height_ = height;
	}

	public void stop() {
		try {
			thread_.interrupt();
			thread_.join();
		} catch (InterruptedException e) {
		}
	}

	public void pause() {
		synchronized (threadLock_) {
			threadPaused_ = true;
		}
	}

	public void resume() {
		synchronized (threadLock_) {
			threadPaused_ = false;
			threadLock_.notifyAll();
		}
	}

	public void running(boolean run) {
		synchronized (threadLock_) {
			threadRunning_ = run;
		}
	}

	public boolean running() {
		boolean run = false;
		synchronized (threadLock_) {
			run = threadRunning_;
		}
		return run;
	}

	public void run() {
		Random rand = new Random();
		while (running()) {

			while (threadPaused_) {
				try {
					synchronized (threadLock_) {
						threadLock_.wait();
					}
				} catch (InterruptedException e1) {
					threadPaused_ = false;
					running(false);
				}
			}
			rand.setSeed(System.nanoTime());
			engine_.addAnimation(rand.nextInt(width_), rand.nextInt(height_));
			// engine_.addAnimation(width_ / 2, height_ / 2);
			try {
				int sleepTime = 0;
				synchronized (threadLock_) {
					sleepTime = interval_;
				}
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				running(false);
			}
		} // end while running
	}// end run

}
